package com.zx.auth.block.service.impl;

import com.zx.auth.block.mapstruct.OAuth2AuthorizationConsentMapStructMapper;
import com.zx.auth.block.modle.OAuth2AuthorizationConsent;
import com.zx.auth.block.param.OAuth2AuthorizationConsentParam;
import com.zx.auth.block.repository.OAuth2AuthorizationConsentRepository;
import com.zx.auth.block.repository.custom.OAuth2AuthorizationConsentCustomRepository;
import com.zx.auth.block.service.IOAuth2AuthorizationConsentService;
import com.zx.auth.block.vo.OAuth2AuthorizationConsentVO;
import com.zx.core.context.TenantContextHolder;
import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ObjectWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.core.wrapper.ResponseWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * OAuth2授权同意管理服务实现类
 * 实现OAuth2授权同意的业务逻辑
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OAuth2AuthorizationConsentServiceImpl implements IOAuth2AuthorizationConsentService {

    private final OAuth2AuthorizationConsentRepository consentRepository;
    private final OAuth2AuthorizationConsentCustomRepository consentCustomRepository;

    /**
     * 根据客户端ID和主体名称获取OAuth2授权同意信息
     *
     * @param registeredClientId 注册客户端ID
     * @param principalName      主体名称
     * @return 授权同意信息
     */
    @Override
    public ObjectWrapper<OAuth2AuthorizationConsentVO> getAuthorizationConsent(String registeredClientId, String principalName) {
        ObjectWrapper<OAuth2AuthorizationConsentVO> result = new ObjectWrapper<>();
        try {
            // 查询授权同意信息
            // 使用自定义方法，根据注册客户端ID、主体名称和当前租户ID查找授权同意信息
            Optional<OAuth2AuthorizationConsent> consentOptional = consentCustomRepository.findByRegisteredClientIdAndPrincipalNameAndTenantId(registeredClientId, principalName, TenantContextHolder.getTenantId());
            if (consentOptional.isPresent()) {
                // 转换为VO对象
                OAuth2AuthorizationConsentVO consentVO = OAuth2AuthorizationConsentMapStructMapper.INSTANCE.consentToConsentVO(consentOptional.get());
                result.setData(consentVO);
            }
        } catch (Exception e) {
            log.error("获取授权同意信息时发生错误", e);
            result.fail("获取授权同意信息时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询OAuth2授权同意列表
     *
     * @param consentParam 授权同意参数
     * @return 授权同意列表
     */
    @Override
    public PageWrapper<OAuth2AuthorizationConsentVO> listAuthorizationConsents(OAuth2AuthorizationConsentParam consentParam) {
        PageWrapper<OAuth2AuthorizationConsentVO> result = new PageWrapper<>();

        try {
            // 使用PageInfo帮助类处理分页计算，统一项目中的分页处理逻辑
            PageInfo pageInfo = new PageInfo(consentParam.getPageNum(), consentParam.getPageSize());

            // 创建分页对象
            Pageable pageable = PageRequest.of(
                    pageInfo.getPageNum().intValue(),
                    pageInfo.getPageSize().intValue()
            );

            // 使用自定义仓库进行分页查询
            Page<OAuth2AuthorizationConsent> authorizationConsentsByPage = consentCustomRepository.findAuthorizationConsentsByPage(consentParam, pageable, TenantContextHolder.getTenantId());

            // 转换为VO对象
            List<OAuth2AuthorizationConsentVO> voList = authorizationConsentsByPage.getContent().stream()
                    .map(OAuth2AuthorizationConsentMapStructMapper.INSTANCE::consentToConsentVO)
                    .collect(Collectors.toList());

            // 设置返回结果
            result.setData(voList);
            result.setTotal(authorizationConsentsByPage.getTotalElements());
            result.setCurrentPageNum(consentParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("分页查询授权同意时发生错误", e);
            result.fail("分页查询授权同意时发生错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 删除OAuth2授权同意信息
     *
     * @param registeredClientId 注册客户端ID
     * @param principalName      主体名称
     * @return 删除结果
     */
    @Override
    public ResponseWrapper deleteAuthorizationConsent(String registeredClientId, String principalName) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 业务验证 - 查询授权同意是否存在
            // 使用自定义方法，根据注册客户端ID、主体名称和当前租户ID查找授权同意信息
            Optional<OAuth2AuthorizationConsent> consentOptional = consentCustomRepository.findByRegisteredClientIdAndPrincipalNameAndTenantId(registeredClientId, principalName, TenantContextHolder.getTenantId());

            if (consentOptional.isEmpty()) {
                result.fail("授权同意信息不存在: " + registeredClientId + ", " + principalName);
                return result;
            }

            // 验证租户权限 - 确保只能删除当前租户的数据
            // 虽然查询结果应该是当前租户的数据，但为了安全起见，再次验证
            OAuth2AuthorizationConsent consent = consentOptional.get();

            // 安全比较租户ID，防止跨租户操作
            if (!TenantContextHolder.getTenantId().equals(consent.getTenantId())) {
                result.fail("非当前租户的数据，不能删除");
                return result;
            }

            // 删除授权同意
            consentRepository.delete(consent);
        } catch (Exception e) {
            log.error("删除授权同意时发生错误", e);
            result.fail("删除授权同意时发生错误: " + e.getMessage());
        }
        return result;
    }
}